package com.sinn.gitrepobranchcompare.config;

import com.sinn.gitrepobranchcompare.tool.Tool;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Properties;

@Data
@Setter
@Getter
public class GitRepoScanConfig {

    private static GitRepoScanConfig config;

    private String appName;
    private String compareMethod;
    private String localDir;
    private String tempDir;
    private String resultDir;
    private String repoType;
    private String onlineLink;
    private ArrayList<String> repoList;
    private String sourceBranch;
    private String targetBranch;
    private String greyBranch;

    public static GitRepoScanConfig getGitRepoScanConfig(){
        if (config == null) {
            initConfigAndResources();
        }
        return config;
    }

    public static void setConfig(Properties properties) {
        initConfigAndResources(properties);
    }

    private static void initConfigAndResources(Properties props) {
        try {
            String pAppName = props.getProperty("app_name");
            String pCompareMethod = props.getProperty("compare_method");
            String pLocalDir = props.getProperty("git_process_local_dir");
            String pTempDir = props.getProperty("git_process_temp_dir");
            String pResultDir = props.getProperty("git_process_result_dir");
            String pRepoType = props.getProperty("git_repo_type");
            String pOnlineLink = props.getProperty("git_repo_online_link");
            String pRepoList = props.getProperty("git_scan_repo_list");
            String pSourceBranch = props.getProperty("compare_branch_source");
            String pTargetBranch = props.getProperty("compare_branch_target");
            String pGreyBranch = props.getProperty("compare_branch_grey");

            config = new GitRepoScanConfig();
            config.setAppName(pAppName);
            if (pCompareMethod.equals("online") || pCompareMethod.equals("local")) {
                config.setCompareMethod(pCompareMethod);
            } else {
                System.out.println("初始化代码库扫描配置出错，请检查");
                System.out.println("规则配置1：compare_method仅支持配置 online-在线拉取Git代码库扫描，local-直接读取本地配置文件扫描");
                return;
            }

            boolean bLocalDir = Tool.checkAndBuildFilePath(pLocalDir);
            if (!bLocalDir) {
                return;
            }
            config.setLocalDir(pLocalDir);

            Tool.deleteFileOrDirectory(pTempDir);
            boolean bTempDir = Tool.checkAndBuildFilePath(pTempDir);
            if (!bTempDir) {
                return;
            }
            config.setTempDir(pTempDir);

            boolean bResultDir = Tool.checkAndBuildFilePath(pResultDir);
            if (!bResultDir) {
                return;
            }
            config.setResultDir(pResultDir);

            if (!pRepoType.equals("GitHub") && !pRepoType.equals("Gitee")) {
                System.out.println("初始化代码库扫描配置出错，请检查");
                System.out.println("规则配置2：git_repo_type 代码库类型仅支持GitHub 和 Gitee");
                return;
            }
            config.setRepoType(pRepoType);

            config.setOnlineLink(pOnlineLink);

            String [] repoLists = pRepoList.split(",");
            ArrayList<String> repoListArr = new ArrayList<>();
            Collections.addAll(repoListArr, repoLists);
            config.setRepoList(repoListArr);

            if (pSourceBranch.isEmpty()) {
                System.out.println("初始化代码库扫描配置出错，请检查");
                System.out.println("规则配置3：compare_branch_source 代码库扫描源分支为空");
                return;
            }
            config.setSourceBranch(pSourceBranch);

            if (pTargetBranch.isEmpty() && pGreyBranch.isEmpty()) {
                System.out.println("初始化代码库扫描配置出错，请检查");
                System.out.println("规则配置4：compare_branch_target 代码库扫描目标分支和 compare_branch_grey 代码库扫描灰度分支不能同时为空");
                return;
            }
            config.setTargetBranch(pTargetBranch);
            config.setGreyBranch(pGreyBranch);

            System.out.println("代码库比对配置文件读取成功");

            Tool.checkAndBuildFilePath(pLocalDir + File.separator + "source");
            Tool.checkAndBuildFilePath(pLocalDir + File.separator + "target");
            Tool.checkAndBuildFilePath(pLocalDir + File.separator + "grey");
            Tool.checkAndBuildFilePath(pTempDir + File.separator + "source");
            Tool.checkAndBuildFilePath(pTempDir + File.separator + "target");
            Tool.checkAndBuildFilePath(pTempDir + File.separator + "grey");

            generateLog();

        } catch (Exception e) {
            System.out.println("代码库比对配置文件读取失败");
            e.printStackTrace();
        }
    }

    /**
     * # application config
     */
    private static void initConfigAndResources() {
        Properties props = new Properties();
        InputStream inputStream = ClassLoader.getSystemResourceAsStream("git-repo-scan-config.properties");
        try {
            props.load(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        initConfigAndResources(props);
    }

    private static void generateLog() {
        StringBuilder sb = new StringBuilder();

        sb.append(config.getAppName());
        sb.append("\t");
        sb.append(config.getCompareMethod());
        sb.append("\t");
        sb.append(config.getLocalDir());
        sb.append("\t");
        sb.append(config.getTempDir());
        sb.append("\t");
        sb.append(config.getResultDir());
        sb.append("\t");
        sb.append(config.getRepoType());
        sb.append("\t");
        sb.append(config.getOnlineLink());
        sb.append("\t");
        sb.append(config.getSourceBranch());
        sb.append("\t");
        sb.append(config.getTargetBranch());
        sb.append("\t");
        sb.append(config.getGreyBranch());
        sb.append("\t");
        String strBefore = sb.toString();
        sb = new StringBuilder();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (String repo: config.getRepoList()) {
            sb.append(strBefore);
            sb.append(repo);
            sb.append("\t");
            sb.append(sdf.format(new Date()));
            sb.append("\r\n");
        }
        String outputFile = config.getResultDir() + File.separator + "git_repo_config.txt";
        Tool.appendToFile(outputFile, sb);
    }

}
